<!-- 隐患汇总 -->
<template>
	<view class="resgistration-container">

		<uni-forms ref="hiddenForm" :rules="rules" :modelValue="hiddenForm" border>
			<uni-forms-item label="检查负责人：" name="examineExecutorName">
				<uni-easyinput v-model="hiddenForm.examineExecutorName" disabled placeholder="请输入"
					:inputBorder="false" />
			</uni-forms-item>
			<uni-forms-item label="检查时间：" required name="taskTime">
				<uni-easyinput v-model="hiddenForm.taskTime" placeholder="请输入" disabled :inputBorder="false" />
			</uni-forms-item>

			<!-- 上面选择检查计划回写上来的 -->
			<uni-forms-item label="计划上报时间：" required name="plannedReportingTime">
				<uni-datetime-picker type="date" :start="startDate" :end="endDate" :clear-icon="false"
					v-model="hiddenForm.plannedReportingTime" />
			</uni-forms-item>

			<uni-forms-item label="上传检查图片：" required name="hiddenDangerDeptName">

				<uni-file-picker v-model="fileLists" @select="handleSelect" @success="handleSuccess"
					@delete="handleDeleteImg" :imageStyles="imageStyles" file-mediatype="image">
				</uni-file-picker>

			</uni-forms-item>



		</uni-forms>
		<uni-segmented-control :current="current" :values="items" style-type="text" @clickItem="changeTable" />
		<template v-if="current == 0">
			<view class="table-container">
				<uni-table ref="table" :loading="loading" border stripe type="selection" emptyText="暂无更多数据"
					@selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center" width="90">序号</uni-th>
						<uni-th align="center" width="120">隐患名称</uni-th>
						<uni-th align="center" width="140">隐患描述</uni-th>
						<uni-th align="center" width="100">隐患等级</uni-th>
						<uni-th align="center" width="110">是否现场解决</uni-th>
						<uni-th align="center" width="100">提交人</uni-th>
						<uni-th align="center" width="100">提交时间</uni-th>
						<uni-th align="center" class="fixed" width="140">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item, index) in hiddenData" :key="index">
						<uni-td>{{ index +1 }}</uni-td>
						<uni-td>
							<view class="name">{{ item.hiddenDangerName }}</view>
						</uni-td>
						<uni-td align="center">{{ item.hiddenDangerDescription }}</uni-td>
						<uni-td align="center">{{ formatDangerLevel(item.hiddenDangerLevel)  }}

						</uni-td>
						<uni-td align="center">{{ formatSolution(item.isSiteSolution) }}</uni-td>
						<uni-td align="center">{{item.createBy}}</uni-td>
						<uni-td align="center">{{item.createTime}}</uni-td>
						<uni-td align="center" class="fixed">
							<view class="uni-group">
								<button class="uni-button" size="mini" type="primary"
									@click="handleEdit(item)">修改</button>
								<button class="uni-button" size="mini" type="warn"
									@click="handleDelete(item)">删除</button>

							</view>
						</uni-td>
					</uni-tr>
				</uni-table>

			</view>

		</template>

		<template v-else-if="current == 1">
				<uni-table ref="table" :loading="loading" border stripe type="selection" emptyText="暂无更多数据"
					@selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center">序号</uni-th>
						<uni-th align="center">检查人名单</uni-th>
						<uni-th align="center">是否提交</uni-th>
						<uni-th align="center">提交数量</uni-th>
						<uni-th align="center" class="fixed-two">提交时间</uni-th>
					</uni-tr>
					<uni-tr v-for="(item, index) in userFillData" :key="index">
						<uni-td>{{ index +1 }}</uni-td>
						<uni-td>
							<view class="name" align="center">{{ item.userName }}</view>
						</uni-td>
						<uni-td align="center">
							<template v-if="item.whetherToFillIn == 1">
								<text>是</text>
							</template> <template v-else-if="item.whetherToFillIn == 2">
								<text>否</text>
							</template>
						</uni-td>
						<uni-td align="center">{{ item.fillInQuantity }}</uni-td>
						<uni-td align="center" class="fixed-two">{{ item.fillingTime }}</uni-td>
					</uni-tr>
				</uni-table>
		</template>


		<view class="button">
			<button type="default" class="mini-btn" size="mini" @click="cancel"> 取消 </button>
			<button type="primary" class="mini-btn" size="mini" @click="onSubmit"> 确认 </button>
		</view>



	</view>

</template>

<script>
	import {
		mapGetters
	} from "vuex"

	import {
		sendRegular,
		detailRegister,
		detailViewRegister
	} from "@/api/hiddenTrouble/periodShoot.js";
	import dayjs from 'dayjs';
	import {
		deptTreeSelect
	} from "@/api/system/user";
	export default {
		onLoad(e) {
			const eventChannel = this.getOpenerEventChannel();
			eventChannel.on('acceptDataFromOpenedPage3', (data) => {
				this.checkId = data.checkId
				this.currentTag = true
				// console.log("进来了", data)
				this.detailObj = data.totalObj
				this.handleOpen(this.detailObj.summaryThree)


			})
		},

		data() {
			return {
				checkFileList: [],
				fileList: [],
				imageStyles: {
					width: 64,
					height: 64,
					border: {
						radius: ''
					}
				},
				//开始日期
				startDate: null,
				//结束日期
				endDate: null,
				fileLists: [],
				//选中ID
				checkId: null,
				//加载中
				loading: false,
				//隐患登记表
				hiddenData: [],
				//人员填报表
				userFillData: [],
				//检查图片列表
				hiddenFileInfoList: [],
				//当前选中
				current: 0,
				//标签
				items: ['隐患登记表', '人员填报表'],
				//详情
				detailObj: {},
				//校验规则
				rules: {},
				//标记
				currentTag: false,
				//部门数据
				treeData: [],
				//隐患登记
				hiddenForm: {
					isSiteSolution: 2,
					fileInfoList: []
				},
				hiddenLevelOption: [{
						text: '一般隐患',
						value: 1
					},
					{
						text: '重大隐患',
						value: 2
					},

				],
				solveOption: [{
						text: '是',
						value: 1
					},
					{
						text: '否',
						value: 2
					},
				],
			}
		},
		methods: {
			//上传成功
			handleSuccess(val) {
				// console.log("上传成功", val)
			},

			//删除
			handleDeleteImg(val) {
				// console.log("删除成功", val)

			},
			checkDate() {
				// 使用示例
				let specificDate = this.detailObj.summaryThree.taskTime; // 特定日期
				let newDate = this.getDateAfterFifteenDays(specificDate); //特定日期15天后的
				this.startDate = specificDate;
				this.endDate = newDate.toISOString().split('T')[0]
			},
			getDateAfterFifteenDays(dateString) {
				// 如果dateString是一个日期字符串，我们需要先将其转换为Date对象
				let date = new Date(dateString);

				// 检查日期是否有效
				if (isNaN(date.getTime())) {
					throw new Error('Invalid date string');
				}

				// 将日期往后推15天
				date.setDate(date.getDate() + 15);

				// 返回新的日期
				return date;
			},



			//格式化隐患等级
			formatDangerLevel(val) {
				switch (val) {
					case 1:
						return "一般隐患";
					case 2:
						return "重大隐患";
					default:
						break;
				}
			},
			//格式化是否现场解决
			formatSolution(val) {
				switch (val) {
					case 1:
						return "是";
					case 2:
						return "否";
					default:
						break;
				}
			},
			//格式化现场解决
			//修改按钮
			async handleEdit(row) {
				let {
					data
				} = await detailRegister(row.id);
				uni.navigateTo({
					url: '/pages/trouble/process/registration',
					success: function(res) {
						// 通过eventChannel向被打开页面传送数据
						res.eventChannel.emit('acceptDataFromOpenerPage', {
							data: data
						})
					}
				})
			},
			//选择文件
			handleSelect(res) {
				// console.log("选择文件", res)
				let tempFiles = res.tempFiles[0]
				this.hiddenForm.fileInfoList.push({
					name: tempFiles.name,
					fileId: tempFiles.uuid,
					type: 24 //上传检查图片
				})
			},
			//删除隐患登记表数据
			handleDelete(row) {
				this.hiddenData.map((item, index) => {
					if (item.id == row.id) {
						this.hiddenData.splice(index, 1);
					}
				});
			},
			//切换table表
			async changeTable(e) {
				// if(e && e.currentIndex){
				this.current = e.currentIndex
				this.currentTag = this.current == 0 ? true : false
				// }

			},
			//取消按钮
			cancel() {
				uni.navigateBack({
					delta: 1, //返回层数，2则上上页
				})
			},
			/** 提交按钮 */
			onSubmit() {

				this.$refs.hiddenForm.validate().then(async (res) => {

					let query = {
						id: this.checkId,
						plannedReportingTime: this.hiddenForm.plannedReportingTime,
						fileInfoList: this.hiddenForm.fileInfoList,
					};
					// console.log("提交参数", query, this.hiddenForm, this.fileLists);
					uni.showLoading({
						title: "提交中"
					})
					let response = await sendRegular(query);
					uni.navigateTo({
						url: "/pages/trouble/index"
					})
					uni.hideLoading()

				}).catch(err => {
					// console.log('表单错误信息：', err);
				})


			},
			handleOpen(data) {
				// console.log("data===", data)
				this.hiddenForm = data;
				this.fileList = data.fileInfoList;
				this.hiddenData = data.hiddentroubleInspectionRegisters;
				this.userFillData = data.personnelFillingForms;
				if (this.operateStatus == 0) {
					this.fileList = data.fileInfoList?.filter((item) => {
						return item.type == 25;
					});
					this.checkFileList = data.fileInfoList?.filter((item) => {
						return item.type == 24;
					});
				}
			},
			/** 被检查部门部门下拉树结构 */
			async getDeptTree() {
				const response = await deptTreeSelect();
				this.treeData = response.data;
			},
		},
		mounted() {

			// this.handleOpen()
			this.getDeptTree()
			this.changeTable()
			this.checkDate()

		},

		watch: {
			currentTag: {
				async handler(val) {

					if (val == true) {
						let query = {
							regularId: this.checkId,
						};
						let res = await detailViewRegister(query);
						this.hiddenData = res.rows;
					} else if (val == false) {

						this.userFillData = this.detailObj.summaryThree.personnelFillingForms;
					}

				},
				deep: true
				// immediate: true
			}
		},
		computed: {
			...mapGetters(["allUsers"]),

		}
	}
</script>

<style lang="scss" scoped>
	.resgistration-container {
		padding: 20rpx;
		background-color: #fff;
		overflow-y: auto;
		height: 100vh;

		.table-container {

			.fixed {
				width: 170px !important;
				position: sticky;
				right: 0;
				z-index: 2;
				background-color: #ffffff;
			}
		}
			

		.button {
			text-align: right;
			margin: 10rpx;


			.mini-btn {
				margin-right: 10px !important;
			}
		}

		::v-deep {
			.uni-forms-item--border {
				border-top: 0 solid #000;
				border-bottom: 2rpx solid #e8eaec;
			}

			.uni-forms-item__label {
				width: 40% !important;
			}

			.submit-btn {
				margin-top: 30rpx;
				background: #137ee9;
				border-radius: 10rpx;
			}
		}
	}
</style>